package top.huhuiyu.springboot2.study.interceptor;

import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Arrays;
import java.util.Map;

/**
 * @author 胡辉煜
 */
@Slf4j
@Component
@RequiredArgsConstructor
public class AppInterceptor implements HandlerInterceptor {

  @Override
  public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
    log.debug("请求前置处理");
    // 获取请求的相关信息
    log.debug("请求路径：{}", request.getRequestURI());
    log.debug("请求方法：{}", request.getMethod());
    // 获取请求参数(不能获取body中的json参数)
    Map<String, String[]> params = request.getParameterMap();
    params.forEach((k, v) -> {
      log.debug("请求参数：{} = {}", k, Arrays.toString(v));
    });
    // 判断拦截的是否是控制器
    if (handler instanceof HandlerMethod) {
      log.debug("访问的是控制器");
      HandlerMethod hm = (HandlerMethod) handler;
      log.debug("控制器：{}", hm.getBeanType().getName());
      log.debug("方法：{}", hm.getMethod().getName());
    }

    return true;
  }

  @Override
  public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
    log.debug("请求尾置处理");
  }

  @Override
  public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
    log.debug("拦截器完毕");
  }
}
